<?php
include_once '../icloud_files/system/DB.php';


class AdvModel extends DB {

    public $page_title, $seller_id, $payment_tx_id, $vehicle_state, $year, $make, $model, $car_type, $price, $kms,
        $color, $fuel_type, $gearbox, $doors, $description, $contact_name, $contact_phone,
        $contact_email, $contact_city, $seller_account_type, $tac_accepted, $messages, $adv_id, $picture1,
        $picture2, $picture3, $picture4, $picture5, $picture6, $picture7, $picture8, $picture9, $adv_list,
        $seller_data, $email_data, $min_price, $max_price, $keyword, $recently_added, $most_viewed,
        $error, $require_payments;
/* ------------------------------------------------------------------------------------------------- */



    //BASE FUNCTIONS - LISTS
    public function get_adv_lists($table) {
        $query = $this->db_connection->query("SELECT DISTINCT name FROM lists_".$table." WHERE is_active=1");

        while($row = $query->fetch_assoc()) {
            $this->create_property($table, $row['name']);
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function get_models($make = "Audi", $selected_model = "") {
        $query = $this->db_connection->query("SELECT DISTINCT name FROM lists_models
            WHERE is_active=1 AND make_name='".$make."'");

        //output HTML directly for the select on-page
        echo "<option value=''>-- select --</option>";
        while ($row = $query->fetch_assoc()) {
            if($selected_model==$row['name']) {
                echo "<option value='".$row['name']."' selected>".$row['name']."</option>";
            } else {
                echo "<option value='".$row['name']."'>".$row['name']."</option>";
            }
        }

    }
/* ------------------------------------------------------------------------------------------------- */


    public function get_all_user_ads($user_id, $price, $date) {
        //sort algorithm
        if(!$price && !$date) {
            $sort = "ORDER BY date_added DESC";
        } else if(!$price && $date) {
            $sort = "ORDER BY date_added ".$date;
        } else if($price && !$date) {
            $sort = "ORDER BY price ".$price;
        } else {
            $sort = "ORDER BY price ".$price.", date_added ".$date;
        }

        $query = $this->db_connection->query("(SELECT adv_id, price, description, picture1, is_active, date_added, '0' as is_part
            FROM advertises_cars WHERE seller_id='$user_id')
            UNION
            (SELECT adv_id, price, description, picture1, is_active, date_added, '1' as is_part
            FROM advertises_parts WHERE seller_id='$user_id') "
            .$sort);

        if($query->num_rows < 1) {
            $this->messages[] = 'You have no listed advertises.';
        } else {
            for($i=0; $row = $query->fetch_assoc(); $i++) {
                foreach ($row as $k => $v) {
                    $this->adv_list[$i][$k] = $v;
                }
            }
            //echo "<pre>" . print_r($this, true) . "</pre>";
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function get_all_ads() {

        $query = $this->db_connection->query("(SELECT adv_id, seller_id, is_active, advertises_cars.date_added, '0' as is_part, username
            FROM advertises_cars
            LEFT JOIN users ON seller_id=users.user_id)
            UNION
            (SELECT adv_id, seller_id, is_active, advertises_parts.date_added, '1' as is_part, username
            FROM advertises_parts
            LEFT JOIN users ON seller_id=users.user_id)
            ORDER BY date_added DESC");

        if($query->num_rows < 1) {
            $this->messages[] = 'There are no advertises in the system.';
        } else {
            for($i=0; $row = $query->fetch_assoc(); $i++) {
                foreach ($row as $k => $v) {
                    $this->adv_list[$i][$k] = $v;
                }
            }
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function prepare_adv_inquiry($data) {
        $text = htmlspecialchars(trim($_POST['ask_text']));
        $name = htmlspecialchars(trim($_POST['ask_name']));
        $email = htmlspecialchars(trim($_POST['ask_email']));
        $phone = htmlspecialchars(trim($_POST['ask_phone']));

        if(mb_strlen($text) < 10) {
            $this->messages[] = 'Please enter at least 10 symbols for the comment.';
        }

        if(!filter_var($email, FILTER_SANITIZE_EMAIL)) {
            $this->messages[] = 'Please enter a valid email.';
        }

        if(mb_strlen($name) < 2) {
            $this->messages[] = 'Please enter at least 2 symbols for the name.';
        }

        if(count($this->messages) <= 0) {
            $headers = 'From: '.$email."\r\n".'Reply-To: '.$email."\r\n";
            $send_to = $this->seller_data['email'];

            $title = 'Question from Ahimeh Cars Website : Ad #'.$data->adv_id.' '.$data->make.' '.$data->model;
            $msg_body = "<!DOCTYPE html><html><head></head><body>
                        A user on the Ahimeh Cars Website has sent you a question related to one of
                        your posted advertises. Please find the full text below:<br/><br/>
                        User name: ".$name."<br/>
                        User email: ".$email."<br/>
                        User phone: ".$phone."<br/>
                        User comment: ".$text."<br/><br/>
                        Ahimeh Cars Website, 2014 :
                        <a href='".$_SERVER['HTTP_HOST']."'>".$_SERVER['HTTP_HOST']."</a></body></html>";

            $this->email_data = array($send_to, $title, $msg_body, $headers);
        }
        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function update_inactive() {
        $this->db_connection->query("UPDATE advertises_cars SET is_active=0
            WHERE DATEDIFF(NOW(), date_added) > 120");
        $this->db_connection->query("UPDATE advertises_parts SET is_active=0
            WHERE DATEDIFF(NOW(), date_added) > 120");
    }
/* ------------------------------------------------------------------------------------------------- */



    //ADV HANDLING FUNCTIONS
    public function search_adv($data, $price, $date) {
        $this->car_type = $this->db_connection->real_escape_string(trim($data['car_type']));
        $this->make = $this->db_connection->real_escape_string(trim($data['make']));
        $this->model = $this->db_connection->real_escape_string(trim($data['model']));
        $this->vehicle_state = $this->db_connection->real_escape_string(trim($data['vehicle_state']));
        $this->min_price = (int)$data['min_price'];
        $this->max_price = (int)$data['max_price'];
        $this->kms = (int)$data['kms'];
        $this->keyword = $this->db_connection->real_escape_string(trim($data['keyword']));

        $keyword_search = '';
        if(mb_strlen($this->keyword) > 3) {
            $keyword_search = " MATCH (description) AGAINST('{$this->keyword}') AND ";
        }

        //sort algorithm
        if(!$price && !$date) {
            $sort = "ORDER BY date_added DESC";
        } else if(!$price && $date) {
            $sort = "ORDER BY date_added ".$date;
        } else if($price && !$date) {
            $sort = "ORDER BY price ".$price;
        } else {
            $sort = "ORDER BY price ".$price.", date_added ".$date;
        }



        $query = $this->db_connection->query("SELECT * FROM advertises_cars WHERE
        make LIKE '%{$this->make}%' AND
        car_type LIKE '%{$this->car_type}%' AND
        model LIKE '%{$this->model}%' AND
        vehicle_state LIKE '%{$this->vehicle_state}%' AND
        price > $this->min_price AND price < $this->max_price AND
        kms < $this->kms AND
        $keyword_search
        is_active=1 ".$sort);

        if($query->num_rows < 1) {
            $this->messages[] = 'No results found, please try a different search.';
        } else {
            for($i=0; $row = $query->fetch_assoc(); $i++) {
                foreach ($row as $k => $v) {
                    $this->adv_list[$i][$k] = $v;
                }
            }
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function check_adv($data, $type = "car") {

        //input norm, valid, checks
        if($type == "car") {
            $this->payment_tx_id = $this->db_connection->real_escape_string(trim($data['payment_tx_id']));
            $this->vehicle_state = $this->db_connection->real_escape_string(trim($data['vehicle_state']));
            $this->car_type = $this->db_connection->real_escape_string(trim($data['car_type']));
            $this->kms = (int)preg_replace('/\s+/', '', $data['kms']);
            $this->color = $this->db_connection->real_escape_string(trim($data['color']));
            $this->fuel_type = $this->db_connection->real_escape_string(trim($data['fuel_type']));
            $this->gearbox = $this->db_connection->real_escape_string(trim($data['gearbox']));
            $this->doors = $this->db_connection->real_escape_string(trim($data['doors']));
        }

        $this->seller_id = (int)$data['seller_id'];
        $this->year = (int)$data['year'];
        $this->make = $this->db_connection->real_escape_string(trim($data['make']));
        $this->model = $this->db_connection->real_escape_string(trim($data['model']));
        $this->price = (int)preg_replace('/\s+/', '', $data['price']);
        $this->description = $this->db_connection->real_escape_string(trim($data['description']));
        $this->contact_name = $this->db_connection->real_escape_string(trim($data['contact_name']));
        $this->contact_phone = $this->db_connection->real_escape_string(trim($data['contact_phone']));
        $this->contact_email = $this->db_connection->real_escape_string(trim($data['contact_email']));
        $this->contact_city = $this->db_connection->real_escape_string(trim($data['contact_city']));
        $this->tac_accepted = (int)$data['tac'];

        //get seller account type
        $query = $this->db_connection->query("SELECT account_type FROM users WHERE user_id=".$this->seller_id);
        $user_data = $query->fetch_assoc();
        $this->seller_account_type = $user_data['account_type'];

        //data validation
        $this->messages = array();
        $this->error = array();


        //curl - check for successful payment via POST request to paypal
        if($type == "car" && $this->require_payments === true) {
            $pmnt = 0;

            $ch = curl_init();

            curl_setopt($ch, CURLOPT_URL,"https://www.paypal.com/cgi-bin/webscr");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,
                http_build_query(array('cmd' => '_notify-synch',
                    'tx' => $this->payment_tx_id,
                    'at' => 'ZW19hYLnVWlfeZrokH0s3G6-DF5yMM7NlMWkV3X--TriZN4ewt_k8HblDGm')));

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $server_output = curl_exec($ch);
            curl_close ($ch);

            //check for valid and unique payment
            $paym_error = false;
            if (substr($server_output, 0, 7) != "SUCCESS") {
                $this->error[] = "Paypal: FAIL";
            }

            if(strpos($server_output, "receiver_email=viwanu%40gmail.com") == false) {
                $this->error[] = "Paypal: Wrong receiver email";
            }

            if(strpos($server_output, "payment_status=Completed") == false) {
                $this->error[] = "Paypal: Transaction is not completed";
            }

            //check for repeating transaction number
            $tx_check = $this->db_connection->query("SELECT payment_tx_id FROM advertises_cars WHERE payment_tx_id='$this->payment_tx_id'");
            if($tx_check->num_rows > 0) {
                $this->error[] = "Paypal: Transaction number was already used";
            }

            if (count($this->error) < 1) {
                $this->error['ok'] = true;
            } else {
                $this->messages[] = 'Please complete the payment first in order to post the advertise.';
                return $this;
            }
        }



        if(($type == "car" && (empty($this->vehicle_state) || empty($this->color))) ||
            empty($this->contact_name) || empty($this->contact_phone) ||
            ($type != "car" && empty($this->year))) {
            $this->messages[] = 'Please fill in all required fields (marked with * ).';
        }

        if($this->price < 1) {
            $this->messages[] = 'Please enter a valid price, for example: 15500 .';
        }

        if(!filter_var($this->contact_email, FILTER_SANITIZE_EMAIL)) {
            $this->messages[] = 'Please enter a valid email.';
        }

        if($this->tac_accepted != 1) {
            $this->messages[] = 'In order to use our services you need to read and accept our Advertiser Terms and Conditions first.';
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function upload_pics($pics, $type = "car"){
        foreach ($pics as $k => $v) {
            if($v['error'] == UPLOAD_ERR_OK) {
                $tmp_path = $v['tmp_name'];
                $dir =  'img/user_data/seller_id_'.$this->seller_id.'/'.$type.'_advertise_id_'.$this->adv_id.'/';
                if(!is_dir($dir)) {
                    mkdir($dir, 0777, true);
                }
                $new_path = $dir.$k.'_'.time().'.'.pathinfo($v['name'], PATHINFO_EXTENSION);
                $this->$k = $new_path; //$this->pictureX

                if(!move_uploaded_file($tmp_path, $new_path)) {
                    $this->messages[] = 'Pictures could not be uploaded. Please try again later.';
                }
            }
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function delete_pics($adv_id, $user_id, $type = "car"){
        $dir =  'img/user_data/seller_id_'.$user_id.'/'.$type.'_advertise_id_'.$adv_id.'/';

        $files = glob($dir.'*'); // get all file names
        foreach($files as $file) {
            if(is_file($file)) {
                unlink($file);
            }
        }
        if(is_dir($dir)) {
            rmdir($dir);
        }
    }
/* ------------------------------------------------------------------------------------------------- */


    public function add_adv($pics) {
        $result = $this->db_connection->query("INSERT INTO advertises_cars
            VALUES ( DEFAULT,
            '".$this->seller_id."',
            '".$this->payment_tx_id."',
            '".$this->vehicle_state."',
            '".$this->year."',
            '".$this->make."',
            '".$this->model."',
            '".$this->car_type."',
            '".$this->price."',
            '".$this->kms."',
            '".$this->color."',
            '".$this->fuel_type."',
            '".$this->gearbox."',
            '".$this->doors."',
            '".$this->description."',
            '".$this->contact_name."',
            '".$this->contact_phone."',
            '".$this->contact_email."',
            '".$this->contact_city."',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            DEFAULT,
            DEFAULT,
            DEFAULT)");

        $this->adv_id = $this->db_connection->insert_id;

        $this->upload_pics($pics); //upload pictures to server

        //update database with correct picture links
        $result_pics = $this->db_connection->query("UPDATE advertises_cars SET
            picture1='".$this->picture1."',
            picture2='".$this->picture2."',
            picture3='".$this->picture3."',
            picture4='".$this->picture4."',
            picture5='".$this->picture5."',
            picture6='".$this->picture6."',
            picture7='".$this->picture7."',
            picture8='".$this->picture8."',
            picture9='".$this->picture9."'
            WHERE adv_id=".$this->adv_id);

        if($result && $result_pics) {
            $this->messages[] = 'The advertise has been added successfully.';
            $this->success = true;
        } else {
            $this->messages[] = 'There has been a problem with your request. We are sorry for the inconvenience, please try again later.';
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function fetch_adv($adv_id, $user_id, $table = "advertises_cars"){
        $query = $this->db_connection->query("SELECT * FROM ".$table."
            WHERE adv_id='$adv_id' AND (seller_id='$user_id' OR '$user_id'=1)");

        if($query->num_rows !== 1) {
            $this->messages[] = 'Internal error.';
        } else {
            $result = $query->fetch_assoc();
            foreach ($result as $k => $v) {
                $this->$k = $v;
            }
        }
        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function increment_views($adv_id, $table) {
        $this->db_connection->query("UPDATE ".$table." SET views=(views+1) WHERE adv_id=".$adv_id);
    }
/* ------------------------------------------------------------------------------------------------- */


    public function edit_adv($pics) {
        $this->upload_pics($pics); //upload pictures to server

        $result = $this->db_connection->query("UPDATE advertises_cars SET
            vehicle_state='".$this->vehicle_state."',
            year='".$this->year."',
            make='".$this->make."',
            model='".$this->model."',
            car_type='".$this->car_type."',
            price='".$this->price."',
            kms='".$this->kms."',
            color='".$this->color."',
            fuel_type='".$this->fuel_type."',
            gearbox='".$this->gearbox."',
            doors='".$this->doors."',
            description='".$this->description."',
            contact_name='".$this->contact_name."',
            contact_phone='".$this->contact_phone."',
            contact_email='".$this->contact_email."',
            contact_city='".$this->contact_city."',
            picture1='".$this->picture1."',
            picture1='".$this->picture1."',
            picture2='".$this->picture2."',
            picture3='".$this->picture3."',
            picture4='".$this->picture4."',
            picture5='".$this->picture5."',
            picture6='".$this->picture6."',
            picture7='".$this->picture7."',
            picture8='".$this->picture8."',
            picture9='".$this->picture9."'
            WHERE adv_id=".$this->adv_id);

        if($result) {
            $this->messages[] = 'The advertise has been updated successfully.';
        } else {
            $this->messages[] = 'There has been a problem with your request. We are sorry for the inconvenience, please try again later.';
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function remove_adv($user_id, $table, $adv_id) {
        $table = $this->db_connection->real_escape_string(trim($table));
        $adv_id = (int)$adv_id;

        //set table
        if($table == 'car') {
            $table = 'advertises_cars';
        } else {
            $table = 'advertises_parts';
        }

        $this->fetch_adv($adv_id, $user_id, $table);
        if(count($this->messages) < 1) { //there is only one row found and rights are okay
            $query = $this->db_connection->query("DELETE FROM ".$table."
            WHERE adv_id='$adv_id' AND (seller_id='$user_id' OR '$user_id'=1)");

            if($query) {
                $this->messages[] = 'The Advertise has been removed successfully.';
            } else {
                $this->error = true;
                $this->messages[] = 'Internal error. Please try again later.';
            }
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function recently_added($table) {
        $query = $this->db_connection->query("SELECT * FROM ".$table."
            ORDER BY date_added DESC LIMIT 4");

            for($i=0; $row = $query->fetch_assoc(); $i++) {
                foreach ($row as $k => $v) {
                    $this->recently_added[$i][$k] = $v;
                }
            }
        return $this;

    }
/* ------------------------------------------------------------------------------------------------- */


    public function most_viewed($table) {
        $query = $this->db_connection->query("SELECT * FROM ".$table."
            ORDER BY views DESC LIMIT 4");

        for($i=0; $row = $query->fetch_assoc(); $i++) {
            foreach ($row as $k => $v) {
                $this->most_viewed[$i][$k] = $v;
            }
        }
        return $this;

    }
    /* ------------------------------------------------------------------------------------------------- */



    //PARTS ONLY HANDLING FUNCTIONS
    public function search_adv_parts($data, $price, $date) {
        $this->make = $this->db_connection->real_escape_string(trim($data['make']));
        $this->model = $this->db_connection->real_escape_string(trim($data['model']));
        $this->year = (int)$data['year'];
        $this->min_price = (int)$data['min_price'];
        $this->max_price = (int)$data['max_price'];
        $this->keyword = $this->db_connection->real_escape_string(trim($data['keyword']));

        $keyword_search = '';
        if(mb_strlen($this->keyword) > 3) {
            $keyword_search = " MATCH (description) AGAINST('{$this->keyword}') AND ";
        }

        //sort algorithm
        if(!$price && !$date) {
            $sort = "ORDER BY date_added DESC";
        } else if(!$price && $date) {
            $sort = "ORDER BY date_added ".$date;
        } else if($price && !$date) {
            $sort = "ORDER BY price ".$price;
        } else {
            $sort = "ORDER BY price ".$price.", date_added ".$date;
        }

        $query = $this->db_connection->query("SELECT * FROM advertises_parts WHERE
        make LIKE '%{$this->make}%' AND
        model LIKE '%{$this->model}%' AND
        price > $this->min_price AND price < $this->max_price AND
        year > $this->year AND
        $keyword_search
        is_active=1 ".$sort);

        if($query->num_rows < 1) {
            $this->messages[] = 'No results found, please try a different search.';
        } else {
            for($i=0; $row = $query->fetch_assoc(); $i++) {
                foreach ($row as $k => $v) {
                    $this->adv_list[$i][$k] = $v;
                }
            }
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function add_adv_parts($pics) {
        $result = $this->db_connection->query("INSERT INTO advertises_parts
            VALUES ( DEFAULT,
            '".$this->seller_id."',
            '',
            '".$this->year."',
            '".$this->make."',
            '".$this->model."',
            '".$this->price."',
            '".$this->description."',
            '".$this->contact_name."',
            '".$this->contact_phone."',
            '".$this->contact_email."',
            '".$this->contact_city."',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            DEFAULT,
            DEFAULT,
            DEFAULT)");

        $this->adv_id = $this->db_connection->insert_id;

        $this->upload_pics($pics, 'parts'); //upload pictures to server

        //update database with correct picture links
        $result_pics = $this->db_connection->query("UPDATE advertises_parts SET
            picture1='".$this->picture1."',
            picture2='".$this->picture2."',
            picture3='".$this->picture3."',
            picture4='".$this->picture4."',
            picture5='".$this->picture5."',
            picture6='".$this->picture6."',
            picture7='".$this->picture7."',
            picture8='".$this->picture8."',
            picture9='".$this->picture9."'
            WHERE adv_id=".$this->adv_id);

        if($result && $result_pics) {
            $this->messages[] = 'The advertise has been added successfully.';
            $this->success = true;
        } else {
            $this->messages[] = 'There has been a problem with your request. We are sorry for the inconvenience, please try again later.';
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */


    public function edit_adv_parts($pics) {
        $this->upload_pics($pics); //upload pictures to server

        $result = $this->db_connection->query("UPDATE advertises_parts SET
            year='".$this->year."',
            make='".$this->make."',
            model='".$this->model."',
            price='".$this->price."',
            description='".$this->description."',
            contact_name='".$this->contact_name."',
            contact_phone='".$this->contact_phone."',
            contact_email='".$this->contact_email."',
            contact_city='".$this->contact_city."',
            picture1='".$this->picture1."',
            picture1='".$this->picture1."',
            picture2='".$this->picture2."',
            picture3='".$this->picture3."',
            picture4='".$this->picture4."',
            picture5='".$this->picture5."',
            picture6='".$this->picture6."',
            picture7='".$this->picture7."',
            picture8='".$this->picture8."',
            picture9='".$this->picture9."'
            WHERE adv_id=".$this->adv_id);

        if($result) {
            $this->messages[] = 'The advertise has been updated successfully.';
        } else {
            $this->messages[] = 'There has been a problem with your request. We are sorry for the inconvenience, please try again later.';
        }

        return $this;
    }
/* ------------------------------------------------------------------------------------------------- */

}